package com.hilda.HTMLParserTesting.utils;

import java.io.File;
import java.net.URL;

import org.jsoup.helper.StringUtil;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

public class SdCardUtils {
	public static final String IMAGE_FOLDER = "/images/";
	public static final String CSS_FOLDER = "/css/";

	private Context mContext;
	private String mRootFolder = null;

	public SdCardUtils(Context c) {
		mContext = c;
	}

	public static boolean isSdCardAvailable() {
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			// We can read and write the media
			mExternalStorageWriteable = true;
		} else {
			// Something else is wrong. It may be one of many other states, but
			// all we need to know is we can't write
			mExternalStorageWriteable = false;
		}

		return mExternalStorageWriteable;
	}

	/**
	 * Prepare a open File to write or read in
	 * SDCARD/android/project.path/website/
	 * 
	 * @param URL
	 * @return File
	 */
	public File prepareFile(URL url, String where) {
		Log.d("crawDroid", ".SdCardUtils.prepareFile: url = " + url);

		if (TextUtils.isEmpty(url.getHost())) {
			Log.e("crawDroid", ".SdCardUtils.prepareFile: no URL Host!");
			return null;
		}

		File file = null;
		String filename = null;
		
		
		
		filename = url.getHost();
		// String fileName = url.getHost().replace(".", "");
		if (filename.contains(".")) {
			
			String splitFilename[] = filename.split("\\.");
			if (splitFilename != null && splitFilename.length > 0) {
				if(splitFilename[0].contains("www")){
					filename = splitFilename[1];
				}else if(splitFilename.length>2){
					filename = splitFilename[1];
				}else{
					filename = filename.replace(".", "");
				}
				
			}

		}

		Log.d("crawDroid",
				".SdCardUtils.prepareFile: url.getPath() " + url.getPath());

		// Error on query urls and doble slash url paths
		if (url.getPath().contains("//")) {

			Log.e("crawDroid", ".SdCardUtils.prepareFile: Path Contains // "
					+ url.getPath());

			url.getPath().replace("//", "/");

			Log.e("crawDroid",
					".SdCardUtils.prepareFile: Change to: " + url.getPath());
			// return null;
		} else if (url.getQuery() != null) {
			Log.e("crawDroid", ".SdCardUtils.prepareFile: Path Contains query "
					+ url.getQuery());
			return null;
		}

		if (!SdCardUtils.isSdCardAvailable()) {
			Log.e("crawDroid", ".SdCardUtils.prepareFile: no SDCARD available!");
			return null;
		}

		String rootFolderForDownloadContent = createRootFolder(url.getHost())
				+ "/";

		if (url.getPath().length() > 1) {
			if (url.getPath().endsWith("/")) {

				// file = new File(mRootFolder +"/"+url.getPath().split("/")[0]
				// +"/"+ fileName + ".html");
				file = new File(rootFolderForDownloadContent + "/" + filename
						+ ".html");
			} else {
				String[] split = url.getPath().split("/");

				if (where != null) {
					file = new File(mRootFolder + where
							+ split[split.length - 1]);
				} else {
					file = new File(rootFolderForDownloadContent
							+ split[split.length - 1]);
				}
			}

		} else {
			// index file
			file = new File(mRootFolder + "/index.html");
		}

		file.getParentFile().mkdirs();

		Log.d("crawDroid",
				".prepareFile: file.absolutePath " + file.getAbsolutePath());

		return file;
	}

	private String createRootFolder(String rootURL) {
		Log.d("crawDroid", ".SdCardUtils.createRootFolder: url " + rootURL);

		File file = null;

		if (!SdCardUtils.isSdCardAvailable()) {
			Log.e("crawDroid", ".SdCardUtils.createRoot: no SDCARD available!");
			return null;
		}

		file = new File(mContext.getExternalFilesDir(null).getAbsolutePath()
				+ "/" + rootURL + "/");

		file.getParentFile().mkdirs();

		Log.d("crawDroid", ".SdCardUtils.createRootFolder: file.absolutePath "
				+ file.getAbsolutePath());

		if (mRootFolder == null) {
			Log.w("crawDroid", ".SdCardUtils.createRootFolder:"
					+ " this is the root folder for the next downloads!");
			mRootFolder = file.getAbsolutePath();
		}

		return file.getAbsolutePath();

	}
}
